package com.arcgis.app.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.InputStream;
import java.lang.ref.WeakReference;

public class BitMapWorkTask extends AsyncTask <String,Void, Bitmap>{

    WeakReference<ImageView> imageReference;


    public BitMapWorkTask(ImageView imageView) {
        imageReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    protected Bitmap doInBackground(String... strings) {
        return decodeStreamBitmap(strings[0]);
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        // TODO Auto-generated method stub
        if (result != null && imageReference != null) {
            ImageView imageView = imageReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(result);
            }
        }
    }

    public Bitmap decodeStreamBitmap(String uri) {
        Bitmap bitmap = null;
        HttpGet get = new HttpGet(uri);
        try {
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(inputStream, null, options);
            int inSampleSize = calculateInSampleSize(options, 160, 130);
            options.inSampleSize = inSampleSize;
            options.inJustDecodeBounds = false;
            response = client.execute(get);
            entity = response.getEntity();
            inputStream = entity.getContent();
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

}
